import React from 'react';
import { Row, Col ,Button,Input,Form,Select,Modal,InputNumber,Table,message } from 'antd';
import {browserHistory} from 'react-router';
import config from '../../config/config';
import $ from 'jquery';
import getFormatDate from '../../common/getFormatData';
const allRouter=config.router;
const FormItem = Form.Item;
const Option = Select.Option;
const token = sessionStorage.getItem('token');
//判断是否点击了页面中的确定或取消按钮，一旦点击，Unmount时候就不再次执行更新行为。
let isBtnClicked=false;

class PayConfirm1 extends React.Component{
    constructor(props){
        super(props);
        this.state={
            visible:false, //完成支付模态框
            visible1:false,//查看费用明细模态框
            orderInfo:[],//该订单信息
            shouldPayed:0,//应收金额
            discountMoney:0,//减免折扣
            reduceMoney:0,//减免金额
            trueMoney:0,//实收金额
            theChange:0,//找零
            payTime:'',//支付时间
            mamberGrade:[],//会员等级
            feePreviewData:[],//查看费用明细模拟数据
            isMoreThan:false,//减免金额是否大于应收金额
        }
    }
    componentWillMount(){
        console.log(JSON.parse(this.props.location.state));
        if(this.props.location.state){
            //获取订单详情
            let url=allRouter.patientOrigin+'/order/findone?id='+JSON.parse(this.props.location.state).myId;
            $.ajax({
                url: url,
                type: "get",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    console.log(data);
                    if(data.code===200){
                        if (data.data.chargeschedule.length > 0) {
                            data.data.chargeschedule.forEach((ele, i) => {
                                ele.index= i + 1;
                            });
                        }
                        this.setState({
                            orderInfo:data.data,
                            feePreviewData:data.data.chargeschedule,
                        },()=>{
                            console.log('fkshf;lkweghjerkjo');
                            console.log(data.data.chargeschedule);
                            let shouldPayed=0;
                            data.data.chargeschedule.map(item=>{
                                shouldPayed+=(item.p_dismoney-0);
                            });
                            this.setState({
                                shouldPayed:shouldPayed.toFixed(2),
                            })
                        })
                    }
                },
                error:err=>{
                    console.log(err);
                }
            })
        }
    }
    componentDidMount(){}
    componentWillUnmount(){
        if(!isBtnClicked){
            this.payConfirmButton(true)
        }
    }
    //确定收费按钮
    payConfirmButton(isCancel) {
        isBtnClicked=true;
        console.log(isCancel);
        let fieldsValue={};
        let thisState=false;
        if(!isCancel) {
            this.props.form.validateFields((err, fieldsValue1) => {
                if (!err) {
                    fieldsValue=fieldsValue1;
                    if (this.state.theChange < 0) {
                        message.info('实收金额应大于应收金额-减免金额');
                        thisState=true;
                    }
                }else{
                    thisState=true;
                }
            })
        }
        if(thisState){
            return;
        }
        if(this.state.isMoreThan){
            message.info('减免金额应小于应收金额');
            return;
        }
        let myDate=new Date();
        let nowTime1 =getFormatDate(myDate);
        let hour = myDate.getHours()<10?('0'+myDate.getHours()):myDate.getHours();
        let minute = myDate.getMinutes()<10?('0'+myDate.getMinutes()):myDate.getMinutes();
        this.setState({
            payTime: nowTime1+' '+hour+':'+minute
        });
        console.log(fieldsValue);
        let url=allRouter.patientOrigin+'/order/update';
        let receipts=this.state.orderInfo.consumptionmoney-(fieldsValue.reduceMoney?fieldsValue.reduceMoney:0);
        console.log(receipts);
        $.ajax({
            url:url,
            type: "post",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id: this.state.orderInfo._id,//订单的_id
                data:JSON.stringify(
                    {clinicname:this.state.orderInfo.clinicname,//诊所名称
                        department: this.state.orderInfo.department,//科室
                        doctor: this.state.orderInfo.doctor,//医生
                        consumptiontime: this.state.orderInfo.consumptiontime,//  就诊时间
                        consumptionmoney: this.state.orderInfo.consumptionmoney,//   应收金额
                        payer: JSON.parse(this.props.location.state).patientId,//付款人
                        remissionmoney: fieldsValue.reduceMoney?fieldsValue.reduceMoney:0,//减免金额
                        remark:  fieldsValue.remark,//备注
                        receipts: receipts,// 实收金额
                        paystate:isCancel?1:2,//   支付状态 1:待收费    2:已收费   3:已退费
                        paytype: 1,//支付类型
                        orderstate: true, //订单状态  true:有效订单  false:无效订单
                        ordertype: this.state.orderInfo.ordertype,//订单类型
                        paytime: nowTime1+' '+hour+':'+minute,//支付时间
                    })
            },
            success:data=>{
                if(isCancel){
                    message.info('取消支付');
                    console.log(data);
                    // browserHistory.push({pathname:'registerTriage',state:'1'});
                    browserHistory.goBack();
                }else{
                    console.log('支付成功:');
                    console.log(data);
                }
                if(data.code===200){
                    console.log('挂号等级');
                    console.log(this.state.orderInfo.ordertype);
                    if(!isCancel){
                        this.setState({
                            visible:true
                        })
                    }
                }else{
                    message.info('支付失败');
                }
            },
            error:err=>{
                console.log(err);
            }
        })

    }
    //输入减免金额时的onChange函数
    handleDeduction(value){
        console.log(value);
        if(value>this.state.orderInfo.consumptionmoney){
            this.props.form.setFields({
                reduceMoney: { value: value, errors: [new Error('减免金额不能大于应收金额')] },
            });
            this.setState({
                isMoreThan:true,
            })
        }else{
            this.props.form.setFields({
                reduceMoney: { value: value,},
            });
            this.setState({
                isMoreThan:false,
            })
        }
        this.setState({
            discountMoney:((parseFloat(value&&!isNaN(value)?value:0)/(this.state.shouldPayed)*100).toFixed(2))>100?100:(parseFloat(value&&!isNaN(value)?value:0)/(this.state.shouldPayed)*100).toFixed(2),
            reduceMoney:value&&!isNaN(value)?value:0,
        },()=>{
            // console.log(this.state.reduceMoney);
            if(this.state.trueMoney){
                this.setState({
                     theChange:this.state.trueMoney-(this.state.shouldPayed)+(this.state.reduceMoney?this.state.reduceMoney:0)
                })
            }
        })
    }
    //输入减免金额折扣时候调用的onChange函数
    handleDeductionDiscount(e){
        console.log(e.target.value);
        if(e.target.value<=100){
            console.log(this.state.shouldPayed);
            this.setState({
                discountMoney:e.target.value,
                reduceMoney:this.state.shouldPayed*(e.target.value/100),
            },()=>{
                console.log(this.state.reduceMoney);
                if(this.state.trueMoney){
                    this.setState({
                        theChange:this.state.trueMoney-this.state.shouldPayed+(this.state.reduceMoney?this.state.reduceMoney:0)
                    })
                }
            });
            this.props.form.setFieldsValue({
                reduceMoney:this.state.shouldPayed*(e.target.value/100)
            })
        }

    }
    //输入实收金额时调用的函数
    handleMoneyReciption(value){
        value=value&&!isNaN(value)?value:0;
        this.setState({
            trueMoney:value,
            theChange:value-this.state.shouldPayed+this.state.reduceMoney
        })
    }

    //显示模态框，费用预览
    feePreview(){
        this.setState({
            visible1:true
        })
    }
    //取消费用预览模态框
    handleCancel1() {
        this.setState({
            visible1: false,
        });
    }
    //跳转到登录页面
    jumpToRegister(){
        this.setState({ visible: false});
        // browserHistory.push({pathname:'registerTriage',state:'1'});
        browserHistory.goBack();

    }

    render(){
        const {orderInfo}=this.state;
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span:7} };
        const { getFieldDecorator } = this.props.form;
        //费用预览表格
        const FeePreview = [
            {
                title: '收费名称',
                dataIndex: 'p_name',
                width: 200,
            },{
                title: '数量',
                dataIndex: 'p_Number',
                width: 100,
            },{
                title: '单价',
                dataIndex: 'p_price',
                width: 100,
            },{
                title: '规格',
                dataIndex: 'p_speci',
                width: 100,
            },{
                title: '金额',
                width: 100,
                dataIndex: 'p_money',
            },{
                title: '折扣',
                dataIndex: 'p_discount',
                width: 100,
            },{
                title: '折后金额',
                width: 100,
                dataIndex: 'p_dismoney',
            },{
                title: '接诊医生',
                width: 250,
                dataIndex: 'p_doctor',
            }
        ];
        return (
            <div className="container">
                <div className="pay-confirm-box">
                    <div className="show-template">
                        <span>*确认支付</span>
                    </div>
                    <div className="pay-confirm-details">
                        <Row align="middle">
                            <Col span={4}>
                                <p>应收金额</p>
                                <p className="pay-confirm-price">￥{this.state.shouldPayed}</p>
                            </Col>
                            <Col span={5}>
                                <p>订单号</p>
                                <p>{orderInfo.orderid}</p>
                            </Col>
                            <Col span={3}>
                                <p>付款人</p>
                                <p>{JSON.parse(this.props.location.state).name}</p>
                            </Col>
                            <Col span={3}>
                                <p>订单类型</p>
                                <p>{orderInfo.ordertype}</p>
                            </Col>
                            <Col span={3}>
                                <p>支付类型</p>
                                <p>{orderInfo.paytype===1?'现金支付':''}</p>
                            </Col>
                            <Col span={3}>
                                <p>就诊日期</p>
                                <p>{orderInfo.consumptiontime}</p>
                            </Col>
                            <Col span={3}>
                                <Button style={{marginTop:'20px'}} onClick={this.feePreview.bind(this)}>查看明细</Button>
                            </Col>
                        </Row>
                    </div>
                    <div className="pay-confirm-inputs">
                        <FormItem {...{ labelCol: { span: 6 }, wrapperCol: { span: 9} }} label="减免金额">
                            <div style={{display:'flex'}}>
                                {getFieldDecorator('reduceMoney', {
                                    rules: [],
                                })(
                                    <InputNumber placeholder="请输入减免金额,只能为数字" onChange={this.handleDeduction.bind(this)} step={0.01} style={{width:'100%'}} precision={2} min={0} />
                                )}
                                <span style={{width:'200px'}}>(减免折扣：<Input style={{width:'40px',display:'inline',padding:'0px'}} value={this.state.discountMoney} onChange={this.handleDeductionDiscount.bind(this)}/>%)</span>
                            </div>
                        </FormItem>
                    </div>
                    <div className="pay-confirm-inputs">
                        <FormItem {...formItemLayout} label="备注">
                            {getFieldDecorator('remark', {
                                rules: [
                                    { max: 100, message: '最多不能超过200个字符' },
                                    { pattern: /^\S+$/, message: '请不要输入空格'}
                                ],
                            })(
                                <Input placeholder="请输入备注" />
                            )}
                        </FormItem>
                    </div>
                    <div className="pay-confirm-inputs">
                        <FormItem {...formItemLayout} label="实收金额">
                            {getFieldDecorator('trueCash', {
                                rules: [{ required: true, message: '实收金额不能为空' },]
                            })(
                                <InputNumber placeholder="请输入实收金额,只能为数字" precision={2} step={0.01} min={0} style={{width:'100%'}} onChange={this.handleMoneyReciption.bind(this)} />
                            )}
                        </FormItem>
                    </div>
                    <div>
                        <Row>
                            <Col span={6}></Col>
                            <Col span={6}><p className="give-change">找零：<span style={{color:'#40a9ff'}}>￥-{this.state.theChange<0?0.00:this.state.theChange.toFixed(2)}</span></p></Col>
                            <Col span={12}></Col>
                        </Row>
                    </div>
                    <div>
                        <Row type="flex" justify="center">
                            <Col span={6}><Button onClick={this.payConfirmButton.bind(this,true)}>取消支付</Button></Col>
                            <Col span={7}><Button type="primary" size="large" style={{width:'100%'}} onClick={this.payConfirmButton.bind(this,false)}>确定收费</Button></Col>
                            <Col span={11}></Col>
                        </Row>
                    </div>
                    {/*收费成功模态框*/}
                    <Modal title="收费成功"
                           visible={this.state.visible}
                           onCancel={this.jumpToRegister.bind(this)}
                           onOk={this.jumpToRegister.bind(this)}
                           footer={null}
                           width={500}
                    >
                        <div>
                            <Row>
                                <Col span={12}>
                                    <p>订单号：{orderInfo.orderid}</p>
                                </Col>
                                <Col span={12}>
                                    <p>付款人：{JSON.parse(this.props.location.state).name}</p>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    金额：￥{this.state.shouldPayed?(this.state.shouldPayed-this.state.reduceMoney).toFixed(2):''}
                                </Col>
                                <Col span={12}>
                                    <p>支付时间：{this.state.payTime}</p>
                                </Col>
                            </Row>
                        </div>
                        <div className="my-clear-fix">
                            <Button onClick={this.jumpToRegister.bind(this)} type="primary" style={{float:'right'}}>确定</Button>
                        </div>
                    </Modal>
                    {/*费用预览模态框*/}
                    <Modal
                        title='费用预览'
                        visible={this.state.visible1}
                        onCancel={this.handleCancel1.bind(this)}
                        footer={null}
                        className="large-model spgl2-4-1"
                    >
                        <div>
                            <Row>
                                <Col span={24} >
                                    <Table
                                        rowKey="index"
                                        columns={FeePreview}
                                        dataSource={this.state.feePreviewData}
                                        pagination={false}
                                        bordered
                                    />
                                </Col>
                            </Row>
                        </div>
                    </Modal>
                </div>
            </div>
        )
    }
}
const PayConfirm = Form.create()(PayConfirm1);
export default PayConfirm;